package com.kdg.passwordgenerator;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextField;
import javafx.scene.image.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import javax.tools.Tool;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.prefs.Preferences;

/**
 * Created by OzZiE on 9/20/2014.
 */
public class Settings extends Application {

    private boolean DEBUG = GUIMain.DEBUG;

    private Date buildDate = GUIMain.buildDate;      //HIDE LATER ONCE RELEASED
    private DateFormat dFormat= GUIMain.dFormat;     //HIDE LATER ONCE RELEASED
    private MenuBar menuBar = GUIMain.menuBar;

    /*
    public final Preferences userPrefs = Preferences.userRoot().node(this.getClass().getName());

    public static JCheckBox checkClip;
    public static JCheckBox checkLetters;
    public static JCheckBox checkNumbers;
    public static JCheckBox checkSymbols;

    private JButton savePrefs;
    private JButton resetPrefs;
    private JButton close;

    public static JTextField txtLimit;

    private final Misc misc = new Misc();       */

    public Settings() {

    }

    @Override
    public void start(final Stage stage) {

        //Tool tips
        Tooltip tooltip = new Tooltip();
        tooltip.setText("If checked, each generate will automatically copy to clipboard");


        stage.setTitle("KDG Password Generator 2.0 " + dFormat.format(buildDate));     //remove format once released
        Scene scene = new Scene(new VBox(), 400, 300);
        scene.setFill(javafx.scene.paint.Color.AQUA);
        stage.getIcons().add(new javafx.scene.image.Image("file:resources/Small_Logo.png"));

        ((VBox) scene.getRoot()).getChildren().addAll(menuBar);

        stage.setScene(scene);
        stage.show();


        /************* Setting up left grid ***************/
        GridPane leftBox = new GridPane();
       // if(DEBUG)                                    //used to see the GRID
           // leftBox.setGridLinesVisible(true);


        //Checkboxes and labels on left
        CheckBox checkLetters = new CheckBox();
        //checkLetters.setSelected(userPrefs.getBoolean("letters", true));
        Label labelLetters = new Label("Letters");
        labelLetters.setFont(new Font(18));

        CheckBox checkNumbers = new CheckBox();
        //checkNumbers.setSelected(userPrefs.getBoolean("numbers", true));
        Label labelNumbers= new Label("Numbers");
        labelNumbers.setFont(new Font(18));

        CheckBox checkSymbols = new CheckBox();
        //checkSymbols.setSelected(userPrefs.getBoolean("symbols", true));
        Label labelSymbols= new Label("Symbols");
        labelSymbols.setFont(new Font(18));

        leftBox.setVgap(25);

        GridPane.setConstraints(labelLetters, 0,0);
        leftBox.getChildren().add(labelLetters);
        GridPane.setConstraints(checkLetters, 1,0);
        leftBox.getChildren().add(checkLetters);

        GridPane.setConstraints(labelNumbers,0,1);
        leftBox.getChildren().add(labelNumbers);
        GridPane.setConstraints(checkNumbers,1,1);
        leftBox.getChildren().add(checkNumbers);

        GridPane.setConstraints(labelSymbols,0,2);
        leftBox.getChildren().add(labelSymbols);
        GridPane.setConstraints(checkSymbols,1,2);
        leftBox.getChildren().add(checkSymbols);

        leftBox.setMargin(labelLetters, new Insets(40,10,0,40));
        leftBox.setMargin(checkLetters, new Insets(40,0,0,0));
        leftBox.setMargin(labelNumbers, new Insets(0,10,0,40));
        leftBox.setMargin(labelSymbols, new Insets(0,10,0,40));

        leftBox.setMaxSize(200, 200);


        //leftBox.setStyle("-fx-border: 2px solid; -fx-border-color: red; -fx-margin: 0 -20 0 0");    //mess with this



        /************* Setting up right grid ***************/
        GridPane rightBox = new GridPane();
      //  if(DEBUG)
        //    rightBox.setGridLinesVisible(true);       //used to see the GRID

        Label labelPwSize = new Label("Size of Password (3-20)");
        final TextField fieldPwSize = new TextField();
        fieldPwSize.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
                if (fieldPwSize.getText().length() > 2) {
                    String s = fieldPwSize.getText().substring(0, 2);
                    fieldPwSize.setText(s);
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });
        //consume letters or symbols.
        fieldPwSize.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                if (!"0123456789".contains(keyEvent.getCharacter())) {
                    keyEvent.consume();
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        });

        fieldPwSize.setMinWidth(30);
        fieldPwSize.setPrefWidth(30);
        fieldPwSize.setMaxWidth(30);

        Label labelCopy = new Label("Copy to clipboard");
        CheckBox checkClip = new CheckBox();
        checkClip.setTooltip(tooltip);

        //Check boxes and labels on right
        GridPane.setConstraints(labelPwSize, 0, 0);
        rightBox.getChildren().add(labelPwSize);
        GridPane.setConstraints(fieldPwSize, 0, 1);
        rightBox.getChildren().add(fieldPwSize);
        GridPane.setConstraints(labelCopy, 0, 2);
        rightBox.getChildren().add(labelCopy);
        GridPane.setConstraints(checkClip, 0, 3);
        rightBox.getChildren().add(checkClip);

        rightBox.setMargin(labelPwSize, new Insets(40,40,10,0));
        rightBox.setMargin(labelCopy, new Insets(28.2,0,10,0));


        //Setting up the HBOX to hold left and right BOX
        HBox hBox = new HBox();
        hBox.setSpacing(75);
        hBox.setAlignment(Pos.TOP_LEFT);
        hBox.getChildren().add(leftBox);
        hBox.setAlignment(Pos.TOP_RIGHT);
        hBox.getChildren().add(rightBox);


        /********** Setting up bottom grid  **************/
        GridPane bottomBox = new GridPane();
        Button save = new Button("Save");
        Button reset = new Button("Reset");
        Button back = new Button("Back");
        bottomBox.setAlignment(Pos.CENTER);
        GridPane.setConstraints(save, 0,0);
        bottomBox.getChildren().add(save);
        GridPane.setConstraints(reset, 1, 0);
        bottomBox.getChildren().add(reset);
        GridPane.setConstraints(back, 0,1);
        bottomBox.getChildren().add(back);

        bottomBox.setMargin(save, new Insets(30,0,0,0));
        bottomBox.setMargin(reset, new Insets(30,0,0,0));
        bottomBox.setMargin(back, new Insets(15,0,0,45));



        /**************************************  EVENT HANDLING  ***********************************/
        back.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                stage.hide();
            }
        });


        ((VBox) scene.getRoot()).getChildren().addAll(hBox, bottomBox);

        isVisible();

        if(DEBUG)
            System.out.println("Settings Created");

        fieldPwSize.requestFocus();

    }


    //Disable settings menu item so another window cannot be created
    private void isVisible(){
        final Pane root = new Pane();

        if(root.isVisible()){
            GUIMain.settings.setDisable(true);
        }
        if(DEBUG)
            System.out.println("Settings Menu Disabled");
    }


       /*
        GridBagConstraints c = new GridBagConstraints();

        //Layout panels.
        JPanel mainPanel1 = new JPanel(new GridLayout(2, 0));
        JPanel mainPanel2 = new JPanel(new BorderLayout());
        JPanel lPanel = new JPanel(new GridBagLayout());
        lPanel.setBorder(BorderFactory.createTitledBorder("Options"));
        JPanel mPanel = new JPanel(new GridBagLayout());
        JPanel bPanel = new JPanel(new FlowLayout());
        JPanel bPanel2 = new JPanel(new FlowLayout());
        JPanel rPanel = new JPanel(new GridBagLayout());
        rPanel.setBorder(BorderFactory.createTitledBorder("Set"));

        //Labels.
        JLabel labelLetters = new JLabel("Letters");
        JLabel labelNumbers = new JLabel("Numbers");
        JLabel labelSymbols = new JLabel("Symbols");
        JLabel labelLimit = new JLabel("<html>Size of Password <br>(3-20)</html>", SwingConstants.LEFT);
        JLabel labelClip = new JLabel("Copy to clipboard");
        labelClip.setToolTipText("If checked, each generate will automatically copy to clipboard");

        //Checkboxes.
        checkLetters = new JCheckBox();
        checkLetters.setSelected(userPrefs.getBoolean("letters", true));
        checkNumbers = new JCheckBox();
        checkNumbers.setSelected(userPrefs.getBoolean("numbers", true));
        checkSymbols = new JCheckBox();
        checkSymbols.setSelected(userPrefs.getBoolean("symbols", true));
        checkClip = new JCheckBox();
        checkClip.setToolTipText("If checked, each generate will automatically copy to clipboard");

        //Buttons.
        savePrefs = new JButton("Save Preferences");
        savePrefs.addActionListener(new EventListener());
        resetPrefs = new JButton("Reset Preferences");
        resetPrefs.addActionListener(new EventListener());
        close = new JButton("Close");
        close.addActionListener(new EventListener());

        //Limit.
        txtLimit = new JTextField();
        txtLimit.setDocument(new JTextFieldLimit(2));
        txtLimit.setColumns(2);
        txtLimit.setText(userPrefs.get("limit", "7"));

        //consume letters or symbols.
        txtLimit.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                char input = e.getKeyChar();

                if ((input < '0') || (input > '9')) {
                    e.consume();
                }
            }
        });

        //Ensure the text field always gets the first focus.
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent ce) {
                txtLimit.requestFocusInWindow();
            }
        });


        //Left Panel setup.
        c.gridx = 0;
        c.gridy = 0;
        c.ipady = 25;
        c.ipadx = 25;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(labelLetters, c);

        c.gridx = 0;
        c.gridy = 1;
        c.ipady = 25;
        c.ipadx = 25;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(labelNumbers, c);

        c.gridx = 0;
        c.gridy = 2;
        c.ipady = 25;
        c.ipadx = 25;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(labelSymbols, c);

        c.gridx = 1;
        c.gridy = 0;
        c.ipady = 15;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(checkLetters, c);

        c.gridx = 1;
        c.gridy = 1;
        c.ipady = 15;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(checkNumbers, c);

        c.gridx = 1;
        c.gridy = 2;
        c.ipady = 15;
        c.anchor = GridBagConstraints.WEST;
        lPanel.add(checkSymbols, c);


        //right panel setup.
        c.gridx = 0;
        c.gridy = 0;
        c.ipady = 25;
        c.ipadx = 25;
        c.anchor = GridBagConstraints.WEST;
        rPanel.add(labelLimit, c);

        c.gridx = 0;
        c.gridy = 1;
        c.ipady = 25;
        c.ipadx = 25;
        c.anchor = GridBagConstraints.WEST;
        rPanel.add(labelClip, c);

        c.gridx = 1;
        c.gridy = 0;
        c.ipady = 0;
        c.ipadx = 0;
        c.anchor = GridBagConstraints.WEST;
        rPanel.add(txtLimit, c);

        c.gridx = 1;
        c.gridy = 1;
        c.ipady = 15;
        c.anchor = GridBagConstraints.WEST;
        rPanel.add(checkClip, c);

        //bottom panel layout.
        bPanel.add(savePrefs);
        bPanel.add(resetPrefs);

        //bottom panel2 layout
        bPanel2.add(close);

        //Center panel setup.
        c.gridx = 0;
        c.gridy = 0;
        c.ipady = 0;
        c.ipadx = 0;
        c.anchor = GridBagConstraints.CENTER;
        mPanel.add(bPanel, c);

        c.gridx = 0;
        c.gridy = 1;
        c.ipady = 0;
        c.ipadx = 0;
        mPanel.add(bPanel2, c);

        mainPanel2.add(lPanel, BorderLayout.WEST);
        mainPanel2.add(rPanel, BorderLayout.EAST);

        mainPanel1.add(mainPanel2);
        mainPanel1.add(mPanel);

        this.add(mainPanel1);

    }

    private void SaveSettings() {

        if ((!checkLetters.isSelected()) && (!checkNumbers.isSelected()) && (!checkSymbols.isSelected())) {
            JOptionPane.showMessageDialog(getRootPane(), "At least one box must be checked", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            userPrefs.putBoolean("letters", checkLetters.isSelected());
            userPrefs.putBoolean("numbers", checkNumbers.isSelected());
            userPrefs.putBoolean("symbols", checkSymbols.isSelected());
            userPrefs.put("limit", txtLimit.getText());

         }
    }

    private void ResetSettings () {

        userPrefs.remove("letters");
        userPrefs.remove("numbers");
        userPrefs.remove("symbols");
        userPrefs.remove("limit");

        checkLetters.setSelected(true);
        checkNumbers.setSelected(true);
        checkSymbols.setSelected(true);
        txtLimit.setText("7");
        checkClip.setSelected(false);

    }

    class EventListener implements ActionListener {



        @Override
        public void actionPerformed(ActionEvent e) {

            GUIMain main = new GUIMain();

            if (e.getSource() == savePrefs) {
                SaveSettings();
            } else if (e.getSource() == resetPrefs){
                ResetSettings();
            } else if (e.getSource() == close){
             //   main.setCard1Vis();
            }
        }
    }



    //limit character amount in txtLmit
    class JTextFieldLimit extends PlainDocument {
        private final int limit;

        @SuppressWarnings("SameParameterValue")
        JTextFieldLimit(int limit) {
            super();
            this.limit = limit;
        }

        @Override
        public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
            if (str == null)
                return;

            if ((getLength() + str.length()) <= limit) {
                super.insertString(offset, str, attr);

            }
        }


    }  */
}

